#! -*- coding:utf-8 -*-
import os
import json
import logging
from datetime import datetime, timedelta

from common.stats import MG_BIGBANG_COLL as mg
from common.utils import tz


def create_days_ltv(delta=7):
    day = tz.get_utc_date()
    start = day - timedelta(days=delta)
    end = day - timedelta(days=delta - 1)
    cond = {'created_at': {'$gte': start, '$lte': end}}
    t = mg.user_stats.aggregate([
        {"$match": {"created_at": {"$gte": start, "$lt": end}}},
        {"$group": {"_id": None, "count": {"$sum": 1},
                    "price": {"$sum": "$recharge.total"}}}
    ])
    t = t.next() if t.alive else {}
    user_count = t.get('count', 0)
    total_recharge = t.get('price', 0)
    print 'start:{}, end:{}, user count:{}, recharge:{}'.format(start, end, user_count, total_recharge)
    return total_recharge / user_count if user_count else 0


def create_ks_report(day):
    now = tz.local_now()
    day = now
    if now.hour == 0:
        day = day - timedelta(days=1)
    date_str = day.strftime('%Y-%m-%d')
    index = now.hour - 1 if now.hour > 0 else 23
    print 'creating date:%s, index:%s' % (date_str, index)
    key = {
        '_id': '%s-%s' % (date_str, index),
        'day': date_str,
        'index': index,
        'time_start': '%s %d:00' % (date_str, index),
        'time_end': '%s %d:00' % (date_str, index + 1),
    }
    set_data = {}
    # 用户数据
    item = mg.daily_report.find_one({'_id': date_str}) or {}
    new_device = item.get('new_device', 0)  # 新注册
    active_register_user = item.get('active_register_user', 0)  # 绑定总数
    new_user = item.get('new_user', 0)  # 注册绑定
    new_recharge_user = item.get('new_recharge_user', 0)
    active_user = item.get('active_user', 0)
    active_user_ios = item.get('active_user_ios', 0)
    active_user_android = active_user - active_user_ios
    play_user = item.get('play_user', 0)
    day_2_ago = (day - timedelta(1)).strftime('%Y-%m-%d')
    item_2_ago = mg.daily_report.find_one({'_id': day_2_ago}) or {}
    user_stay_2 = float(item_2_ago.get('stay_2', 0)) / item_2_ago.get('new_device')
    day_3_ago = (day - timedelta(3)).strftime('%Y-%m-%d')
    item_3_ago = mg.daily_report.find_one({'_id': day_3_ago}) or {}
    user_stay_3 = float(item_3_ago.get('stay_3', 0)) / item_3_ago.get('new_device')
    day_7_ago = (day - timedelta(7)).strftime('%Y-%m-%d')
    item_7_ago = mg.daily_report.find_one({'_id': day_7_ago}) or {}
    user_stay_7 = float(item_7_ago.get('stay_7', 0)) / item_7_ago.get('new_device')
    recharge_price = item.get('recharge_price', 0)
    recharge_user = item.get('recharge_user', 0)
    recharge_count = item.get('recharge_count', 0)
    agent_recharge_price = item.get('agent_recharge_price', 0)
    agent_recharge_user = item.get('agent_recharge_user', 0)
    new_recharge_price = item.get('new_recharge_price', 0)
    new_recharge_user = item.get('new_recharge_user', 0)
    new_agent_recharge_price = item.get('new_agent_recharge_price', 0)
    new_agent_recharge_user = item.get('new_agent_recharge_user', 0)
    total_tax = item.get('total_tax', 0)
    withdraw_price = item.get('withdraw_price', 0)
    withdraw_user = item.get('withdraw_count', 0)
    real_profit = item.get('profit', 0)
    real_profit_rate = item.get('profit_rate', 0)

    set_data['new_device'] = new_device  # 新注册
    set_data['new_user'] = new_user  # 注册绑定
    set_data['active_register_user'] = active_register_user  # 绑定总数
    set_data['new_recharge_user'] = new_recharge_user
    set_data['new_recharge_device_ratio'] = float(new_recharge_user) / new_device  # 注充率
    set_data['new_register_device_ratio'] = float(new_user) / new_device  # 注绑率
    set_data['new_recharge_ratio'] = float(new_recharge_user) / new_user  # 绑充率
    set_data['active_user'] = active_user
    set_data['active_user_ios'] = active_user_ios
    set_data['active_user_android'] = active_user_android
    set_data['recharge_price'] = recharge_price
    set_data['new_recharge_price'] = new_recharge_price
    set_data['old_recharge_price'] = recharge_price - new_recharge_price
    set_data['online_recharge_price'] = recharge_price - agent_recharge_price
    set_data['new_online_recharge_price'] = new_recharge_price - new_agent_recharge_price
    set_data['old_online_recharge_price'] = set_data['online_recharge_price'] - set_data['new_online_recharge_price']
    set_data['agent_recharge_price'] = agent_recharge_price
    set_data['new_agent_recharge_price'] = new_agent_recharge_price
    set_data['old_agent_recharge_price'] = agent_recharge_price - new_agent_recharge_price
    set_data['recharge_user'] = recharge_user
    set_data['new_recharge_user'] = new_recharge_user
    set_data['old_recharge_user'] = recharge_user - new_recharge_user
    set_data['online_recharge_user'] = recharge_user
    set_data['new_online_recharge_user'] = new_recharge_user
    set_data['old_online_recharge_user'] = recharge_user - new_recharge_user
    set_data['agent_recharge_user'] = agent_recharge_user
    set_data['new_agent_recharge_user'] = new_agent_recharge_user
    set_data['old_agent_recharge_user'] = agent_recharge_user - new_agent_recharge_user
    set_data['recharge_count'] = recharge_count
    set_data['online_recharge_count'] = recharge_count
    set_data['agent_recharge_count'] = 0
    set_data['agent_import'] = 0
    set_data['agent_cost'] = 0
    set_data['agent_balance'] = 0
    set_data['average_recharge'] = float(recharge_price) / recharge_user
    set_data['recharge_rate'] = float(recharge_user) / active_user
    set_data['average_contribute'] = float(total_tax) / recharge_user  # FIXME
    set_data['withdraw_price'] = withdraw_price
    set_data['withdraw_count'] = withdraw_user
    set_data['play_user'] = play_user
    set_data['real_profit'] = real_profit
    set_data['real_profit_rate'] = real_profit_rate
    set_data['user_stay_2'] = user_stay_2
    set_data['user_stay_3'] = user_stay_3
    set_data['user_stay_7'] = user_stay_7
    set_data['arpu'] = float(recharge_price) / active_user
    set_data['arppu'] = float(recharge_price) / recharge_user
    # ltv
    set_data['ltv7'] = create_days_ltv(7)
    set_data['ltv14'] = create_days_ltv(14)
    set_data['ltv30'] = create_days_ltv(30)
    set_data['ltv60'] = create_days_ltv(60)

    mg.interval_report.update_one(
        key, {'$set': set_data}, upsert=True
    )
